#include "main.h"

//LED
uchar led_code;
bit led_n4_en;

//SEG
uchar seg_pos;
uchar seg_str[10];
uchar seg_buf[8] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
uchar seg_mode;

//KEY
uchar key_old;
uchar code kbd_num[] = {6,10,14,18,9,13,17,8,12,16};

//TIMER
ulong timer_count;

//DS1302
uchar DS1302_RTC[] = {13,25,30};

//EEPROM
uint input_val;
uint input_val_old;
bit input_show_en;
bit input_RTC_en = 1;
uchar input_RTC[] = {10,46};


//===========LED=============
void led_proc() {
	if(timer_count%50) return;
	led_code = 0x01 << seg_mode;
	led_n4_en ? led_code |= 0x08 : 1;
}

//===========SEG=============
void seg_proc() {
	if(timer_count%50) return;
	
	switch(seg_mode) {
		case 0:
			DS1302_get_RTC(DS1302_RTC);
			sprintf(seg_str, "%02d-%02d-%02d", (uint)DS1302_RTC[0],
			(uint)DS1302_RTC[1], (uint)DS1302_RTC[2]);
		break;
		case 1:
			input_show_en ? sprintf(seg_str, "C   %4d", input_val) :
			sprintf(seg_str, "C       ");
		break;
		case 2:
			sprintf(seg_str, "E  %02d-%02d", (uint)input_RTC[0], (uint)input_RTC[1]);
		break;
	}
	
	seg_tran(seg_str, seg_buf);
}

//===========KEY=============
void key_proc() {
	uchar i,key_val,key_down;
	if(timer_count%10) return;
	
	//  ⰴ  
	key_val = key_scan_kbd();
	key_down = key_val & (key_old^key_val);
	key_old = key_val;
	
	//     л 
	if(key_down == 4) {
		if(++seg_mode == 3)
			seg_mode = 0;
		input_show_en = 0;
		input_RTC_en = 1;
		
		//   ݴ洢
		if(seg_mode == 2) {
			led_n4_en = (input_val > input_val_old) ? 1 : 0;
			EEPROM_write(0, input_RTC[0]);
			EEPROM_write(1, input_RTC[1]);
			EEPROM_write(2, (uchar)(input_val >> 8));
			EEPROM_write(3, (uchar)(input_val&0x00FF));
			input_val_old = input_val;
			input_val = 0;
		}
	}
	
	//             Ч    
	if(seg_mode == 1) {
		//   
		if(key_down == 5) {
			input_show_en = 0;
			input_val = 0;
			input_RTC_en = 1;
		}
		//    0-9
		if(input_val/1000) return;
		for(i=0; i<10; i++) {
			if(key_down == kbd_num[i]) {
				input_show_en = 1;
				input_val = input_val*10 + i;
				//  ¼        ʱ  
				if(input_RTC_en) {
					input_RTC_en = 0;
					DS1302_get_RTC(DS1302_RTC);
					input_RTC[0] = DS1302_RTC[0];
					input_RTC[1] = DS1302_RTC[1];
				}
			}
		}
	}
	
}

//===========ISR=============
void timer1_init() {
	AUXR &= 0xBF;
	TMOD &= 0x0F;
	TH1 = 0xFC;  //1ms
	TL1 = 0x18;
	TF1 = 0;
	ET1 = 1;
	TR1 = 1;
	EA = 1;
}

void isr_timer_1() interrupt 3 {
	timer_count++;
	
	seg_disp(seg_pos, seg_buf);
	led_disp(led_code);
	if(++seg_pos == 8) seg_pos = 0;
}

//===========MAIN=============
void main() {
	sys_init();
	timer1_init();
	
	DS1302_set_RTC(DS1302_RTC);
	
	while(1) {
		led_proc();
		seg_proc();
		key_proc();
	}
}


